<?php

namespace app\admin\model\post;

use think\Model;


class Comment extends Model
{

    

    

    // 表名
    protected $table = 'post_comment';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    protected $dateFormat='Y-m-d H:i:s';

    // 追加属性
    protected $append = [

    ];



    public function getList($post_id,$page){
        $list = \app\admin\model\post\Comment::with(['user'=>function($query){
            $query->withField('id,nickname,avatar,gender,birthday,bio');
        }])->where('post_id',$post_id)->where('reply_id',0)->order('id desc')->paginate();
        foreach ($list as &$item){
            $item['reply']=$this->getChild($item['id'],$item->user->nickname);
        }
        return $list;
    }


    private function getChild($r_id,$name){
        $data=[];
        $review=self::where(['reply_id'=>$r_id])->with(['user'=>function($query){
            $query->withField('id,nickname,avatar,gender,birthday,bio');
        }])->find();
        if($review){
            $review->title=$review->user->nickname.' 回复 '.$name;
            $data[]=$review;
            $this->getChild($review->id,$review->user->nickname);
        }
        return $data;
    }

    public function getCteatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['cteatetime']) ? $data['cteatetime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCteatetimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function post()
    {
        return $this->belongsTo('app\admin\model\Post', 'post_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'uid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
